package com.itany.interceptor;

import com.itany.ApplicationContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;


public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringRedisTemplate template = ApplicationContextHolder.getBean(StringRedisTemplate.class);
        boolean flag = false;
        Cookie[] cks = request.getCookies();
        if (null != cks) {
            for (int i = 0; i < cks.length; i++) {
                Cookie ck = cks[i];
                if ("TT_TOKEN".equals(ck.getName())) {
                    String token = ck.getValue();
                    String str = template.opsForValue().get("USER_TOKEN::" + token);
                    System.out.println("==============" + str);

                    if (str != null) {
                        flag = true;
                    }
                }
            }
        }
        if (!flag) {
            StringBuffer httpUrl = request.getRequestURL();
            String url = "http://192.168.2.18:9003/user/showlogin?server=" + URLEncoder.encode(httpUrl.toString(), "utf-8");
            response.sendRedirect(url);
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) {

    }
}
